﻿using System.ComponentModel;
using VisualWip.Core;
using VisualWip.Core.Columns;
using VisualWip.Core.Interfaces;

namespace VisualWip.TFS2010Providers
{
    public class TfsWorkSingleQuerySettingsViewModel : TfsWorkQuerySettingsViewModelBase<WorkSingleColumn>
    {
        public TfsWorkSingleQuerySettingsViewModel(Application application, WorkSingleColumn setting,
                                                       IWorkItemProviderFactory workItemProviderFactory,
                                                       IWorkItemSizeProvider workItemSizeProvider,
                                                       IColumnTypeProvider columnTypeProvider)
            : base(application, setting, workItemProviderFactory, workItemSizeProvider, columnTypeProvider)
        {
            AvailableChecked = setting.Availibility;
        }

        public override string SettingsWindowName
        {
            get { return "Tfs single query column settings"; }
        }

        public QueryFolderViewModel Querys { get; protected set; }
        public QueryDefinitionViewModel SelectedQuery { get; set; }

        public bool AvailableChecked
        {
            get { return Column.Availibility; }
            set
            {
                if (value != Column.Availibility)
                {
                    Column.Availibility = value;

                    OnPropertyChanged(this, () => AvailableChecked);
                }
            }
        }

        protected override void Init()
        {
            base.Init();
            if (WorkItemWorkProvider.IsConnected)
            {
                Querys = new QueryFolderViewModel(WorkItemWorkProvider.TeamProject.QueryHierarchy, null);

                var firstQuery = Column.FirstQuery as WorkItemQueryBase;
                Attache(Querys.Children, firstQuery,
                        QueryItemPropertyChanged);

                if (firstQuery != null && firstQuery.DownloadDisplayFieldsOnly)
                    DownloadDisplayFieldsOnly = true;
            }
        }

        private void QueryItemPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            SelectedQuery = sender as QueryDefinitionViewModel;

            if (SelectedQuery == null)
                return;

            SetColumnName(SelectedQuery);

            Column.FirstQuery = CreateWorkItemQuery(SelectedQuery);
        }

        protected override void DownloadDisplayFieldsOnlyHasChanged()
        {
            var firstQuery = Column.FirstQuery as WorkItemQueryBase;

            if (firstQuery != null)
                firstQuery.DownloadDisplayFieldsOnly = DownloadDisplayFieldsOnly;
        }
    }
}